import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import * as actions from '../../actions'

let timer = null

class Type extends Component {

    componentDidMount() {
        this.props.get_Shop_List()
    }

    clickBtn(index) {
        this.props.setIndex(index)
    }

    addShop(item) {
        clearTimeout(timer)
        timer = setTimeout(() => {
            console.log(111)
            this.props.addShop(item)
        }, 1000)
    }

    detailBtn(item) {
        this.props.history.push('/detail')
        this.props.detail_Btn(item)
    }

    render() { 
        let { list, i } = this.props
        return (
            <div className='Type'>
                <div className='left'>
                    <ul>
                        {
                            list && list.length ? list.map((item,index) => {
                                return <li key={index} className={i===index ? 'active' : ''} onClick={
                                    this.clickBtn.bind(this,index)
                                }>{item.title}</li>
                            }) : ''
                        }
                    </ul>
                </div>
                <div className='right'>
                    {
                        list && list.length ? list[i].children.map((item,index) => {
                            return (
                                <div key={index} className='item' onClick={
                                    this.detailBtn.bind(this, item)
                                }>
                                    <img src={item.img} alt='' />
                                    <p>{item.name}</p>
                                    <p>单价：{item.price}</p>
                                    <button onClick={e => {
                                        e.stopPropagation()
                                        this.addShop(item)
                                    }}>加入购物车</button>
                                </div>
                            )
                        }) : ''
                    }
                </div>
            </div>
        )
    }
}

let mapStateToProps = ({shopReducer}) => {
    return {
        ...shopReducer
    }
}

let mapDispatchToProps = (dispatch) => bindActionCreators(actions, dispatch)
 
export default connect(mapStateToProps, mapDispatchToProps)(Type)